import store from "@/store";
import appRouters from "@/router/merge";
import { defineStore } from "pinia";

export const usePermissionStore = defineStore("permission", () => {
  const dynamicRoutes = ref<any>([]);

  // 对动态路由进行筛选
  const filterDynamicRoutes = (powerKey: any, routers: any) => {
    const arr: any = [];
    routers.forEach((item: any) => {
      if (
        powerKey.includes(item.meta?.powerKey) ||
        !item.meta?.powerKey ||
        item.meta?.powerKey === "*"
      ) {
        if (item.children && item.children.length) {
          item.children = item.children.filter((i: any) => {
            return (
              powerKey.includes(i.meta?.powerKey) ||
              !!i.meta?.powerKey ||
              i.meta?.powerKey === "*"
            );
          });
          filterDynamicRoutes(powerKey, item.children);
        }
        arr.push(item);
      }
    });
    return arr;
  };

  const setRouter = (powerKey: any) => {
    const permissionRouters = filterDynamicRoutes(powerKey, appRouters);
    permissionRouters.sort((a: any, b: any) => {
      return a.meta.sort - b.meta.sort;
    });
    dynamicRoutes.value = permissionRouters;
  };

  return {
    dynamicRoutes,
    setRouter,
  };
});

export const usePermissionStoreHook = () => {
  return usePermissionStore(store);
};
